﻿using movie.tool.module.film.model;
using movie.tool.module.response;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;

namespace movie.tool.module.film.service
{
    public class MovieService
    {
        private static readonly NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
        private static readonly MovieService instance = new MovieService();
        public static MovieService Instance => instance;
        private static List<Movie> movies;
        public static List<Movie> Movies => movies;
        private static List<DriveInfo> localDrives = new List<DriveInfo>();

        public void LoadLocalMovies()
        {
            LoadDriveInfo();
            List<Movie> list = new List<Movie>();
            if (localDrives != null && localDrives.Count > 0)
            {
                foreach (DriveInfo di in localDrives)
                {
                    string dir = di.RootDirectory + "data";
                    try
                    {
                        if (Directory.Exists(dir))
                        {
                            foreach (string path in Directory.EnumerateDirectories(dir))
                            {
                                string jsonFile = path + "\\data.json";
                                Movie movie = LoadJsonFileMovie(jsonFile);
                                if (movie != null)
                                {
                                    movie.DriveInfo = di;
                                    movie.Dir = path;
                                    list.Add(movie);
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        logger.Error(ex, "读取目录{0}下的剧本失败", dir);
                    }
                }
            }
            movies = list;
        }

        private static Movie LoadJsonFileMovie(string jsonFile)
        {
            try
            {
                if (File.Exists(jsonFile))
                {
                    string json = File.ReadAllText(jsonFile);
                    if (string.IsNullOrWhiteSpace(json))
                    {
                        return null;
                    }
                   return JsonConvert.DeserializeObject<Movie>(json);
                }
            }
            catch (Exception e)
            {
                logger.Error(e, "读取文件:{0}失败", jsonFile);
            }
            return null;
        }

        private static MovieProject LoadJsonConfig(string jsonFile)
        {
            try
            {
                if (File.Exists(jsonFile))
                {
                    string json = File.ReadAllText(jsonFile);
                    if (string.IsNullOrWhiteSpace(json))
                    {
                        return null;
                    }
                    return JsonConvert.DeserializeObject<MovieProject>(json,OperatorResponse.settings);
                }
            }
            catch (Exception e)
            {
                logger.Error(e, "读取文件:{0}失败", jsonFile);
            }
            return null;
        }

        internal static void SaveProjectMovie(MovieProject localMovie)
        {
            if(localMovie == null)
            {
                return;
            }
            string jsonContent = JsonConvert.SerializeObject(localMovie, OperatorResponse.settings);
            if (!string.IsNullOrEmpty(jsonContent))
            {
                File.WriteAllText(ProjectJsonFile(localMovie.Id), jsonContent);
            }
        }
        internal static void SaveProjectMovie(Movie movie)
        {
            if (movie == null)
            {
                return;
            }
            string jsonContent = JsonConvert.SerializeObject(movie, OperatorResponse.settings);
            if (!string.IsNullOrEmpty(jsonContent))
            {
                File.WriteAllText(MovieOutputFile(movie), jsonContent);
            }
        }

        private void LoadDriveInfo()
        {
            DriveInfo[] dis = DriveInfo.GetDrives();
            foreach (DriveInfo di in dis)
            {
                if (di.DriveType == DriveType.Fixed)
                {
                    localDrives.Add(di);
                }
            }
        }
        /// <summary>
        /// 加载本地对应id的剧本信息
        /// </summary>
        /// <param name="id">剧本id。在项目目录下以剧本id创建的目录就存储对应剧本的所有内容</param>
        /// <returns></returns>
        public static MovieProject LoadProjectMovie(long id)
        {
            string jsonFile = ProjectJsonFile(id);
            MovieProject movie = LoadJsonConfig(jsonFile);
            return movie;
        }
        /// <summary>
        /// 剧本配置文件所在目录
        /// </summary>
        /// <param name="id">剧本id</param>
        /// <returns></returns>
        public static string ProjectJsonFilePath(long id)
        {
            string path = Path.Join(Environment.CurrentDirectory, "projects", string.Format("{0}", id));
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            return path;
        }
        /// <summary>
        /// 下载剧本时的存储目录,也就是可以拿去PC服务器播放的目录
        /// </summary>
        /// <param name="movie">剧本</param>
        /// <returns></returns>
        public static string MovieOutputFilePath(Movie movie)
        {
            string path = Path.Join(Environment.CurrentDirectory, "output", string.Format("{0}", movie.Name));
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            return path;
        }
        /// <summary>
        /// 剧本配置文件的路径
        /// </summary>
        /// <param name="id">剧本id</param>
        /// <returns></returns>
        private static string ProjectJsonFile(long id)
        {
            return Path.Join(ProjectJsonFilePath(id), "data.json");
        }

        private static string MovieOutputFile(Movie movie)
        {
            return Path.Join(MovieOutputFilePath(movie), "data.json");
        }

        public static void SceneNameAndSequence(string fileName, ref string sceneName, ref int sequence)
        {
            if (!string.IsNullOrWhiteSpace(fileName))
            {
                Match match = Regex.Match(fileName, @"^\d+");
                if (match.Success)
                {
                    sequence = int.Parse(match.Value);
                    sceneName = fileName.Substring(match.Value.Length);
                    if (sceneName.StartsWith('.'))
                    {
                        sceneName = sceneName.Substring(1);
                    }
                }
                else
                {
                    sceneName = fileName;
                }
            }
        }
    }
}
